<template>
<div class="data-home" v-loading.fullscreen.lock="detailLoading">
    <div class="box-top">
        <el-form @submit.native.prevent class="form-between">
            <el-form-item label="">
                <el-dropdown trigger="click" @command="handleUploadData">
                    <el-button type="primary">
                        导入数据<i class="el-icon-arrow-down el-icon--right"></i>
                    </el-button>
                    <el-dropdown-menu slot="dropdown">
                        <el-dropdown-item :command="0">本地文件</el-dropdown-item>
                        <el-dropdown-item :command="1">HDFS</el-dropdown-item>
                        <el-dropdown-item :command="2">数据源</el-dropdown-item>
                    </el-dropdown-menu>
                    </el-dropdown>
                <el-button class="check-progress-btn" @click="$router.push('dataSource')">数据源管理</el-button>
                <el-button class="check-progress-btn" @click="$router.push('checkProgress')">查看进度</el-button>
            </el-form-item>
            <el-form-item label="">
                <el-input clearable @clear="search" placeholder="请输入表名" @keyup.enter.native="search" v-model="keyword">
                    <i slot="prefix" class="iconfont icon-sousuo" v-preventReClick="2000" @click="search"></i>
                </el-input>
            </el-form-item>
        </el-form>
    </div>
    <div class="box-table">
        <el-table height="100%" v-loading="loading" :data="tableData" tooltip-effect="dark">
            <template slot="empty">
                <no-data :types="isSearch">
                    <span>暂无数据</span>
                </no-data>
            </template>
            <el-table-column prop="tableName" label="表名" show-overflow-tooltip></el-table-column>
            <el-table-column label="状态" show-overflow-tooltip>
                <template slot-scope="scope">{{scope.row.tableColumns !== -1 ? stateArray[scope.row.tableState] : stateArray[0]}}</template>
            </el-table-column>
            <el-table-column prop="tableColumns" label="字段数" show-overflow-tooltip></el-table-column>
            <el-table-column prop="dataFileSize" label="大小" show-overflow-tooltip>
                <template slot-scope="scope">{{getSize(scope.row.dataFileSize)}}</template>
            </el-table-column>
            <el-table-column prop="createOper" label="创建人" show-overflow-tooltip></el-table-column>
            <el-table-column prop="createTime" label="创建时间" show-overflow-tooltip sortable min-width="125"></el-table-column>
            <el-table-column prop="lastUpdateOper" label="提交人" show-overflow-tooltip></el-table-column>
            <el-table-column prop="lastUpdateTime" label="更新时间" show-overflow-tooltip sortable min-width="125"></el-table-column>
            <el-table-column prop="description" label="描述" show-overflow-tooltip></el-table-column>
            <el-table-column label="操作" width="130px">
                <template slot-scope="scope">
                    <el-button type="text" @click="seeDetail(scope.row)">查看</el-button>
                    <el-divider direction="vertical"></el-divider>
                    <el-button type="text" @click="handleRemove(scope.row)">删除</el-button>
                </template>
            </el-table-column>
        </el-table>
        <div v-if="tableData.length>0" class="box-pagenation">
            <el-pagination @size-change="handleSizeChange" @current-change="handleCurrentChange" :current-page="currentPage" :page-size="pageSize" layout="total, sizes, prev, pager, next, jumper" :total="total">
            </el-pagination>
        </div>
    </div>
    <upload-data v-if="uploadData.show" :addForm="uploadData" @save="saveUpload"></upload-data>
    <data-detail v-if="dialogData.show" :dialogData="dialogData"></data-detail>
</div>
</template>

<script>
import UploadData from './upload'
import DataDetail from './DataDetail'
import NoData from '@/components/NoData'
import {
    mapGetters,
    mapMutations
} from 'vuex'
export default {
    name: 'DataList',
    components: {
        UploadData,
        DataDetail,
        NoData
    },
    data () {
        return {
            uploadData: {
                show: false,
                title: '导入数据',
                form: {
                    dataType: null,
                    databaseType: null,
                    databaseSchema: null,
                    fileList: [],
                    limit: 100,
                    filePath: null,
                    sourceId: null,
                    srcTableName: null,
                    existsHeader: true,
                    characterEncoding: 'UTF-8',
                    timestampFormat: 'yyyy-MM-dd HH:mm:ss.SSS',
                    timeFormat: 'yyyy-MM-dd HH:mm:ss',
                    dateFormat: 'yyyy-MM-dd',
                    columnDelimiter: null,
                    fileType: null,
                    description: null,
                    filed: null,
                    tableName: null,
                    columnsException: 'Discard Row',
                    typeException: 'Missing Value',
                    splitKey: null,
                    errorRecord: null,
                    errorPercentage: null,
                    parallelism: 1,
                    conditionExp: null,
                    inputColumns: [],
                    splitKeyList: [],
                    sparkExecutionNumber: 2,
                    sparkExecutionCores: 2,
                    sparkExecutionMemory: 1024,
                    sparkDriverCores: 1,
                    sparkDriverMemory: 1024
                }
            },
            detailLoading: false,
            loading: false,
            keyword: '',
            total: 0,
            pageSize: 10,
            currentPage: 1,
            tableData: [],
            dialogData: {
                title: '',
                show: false,
                data: {}
            },
            stateArray: ['空表', '正常', '处理中'],
            isSearch: false
        }
    },
    created () {
        this.init()
    },
    computed: {
        ...mapGetters({
            projectId: 'common/getProjectId',
            previewData: 'common/getPreviewData'
        })
    },
    methods: {
        ...mapMutations({
            setShowNodeProp: 'common/setShowNodeProp',
            setUpdateDataTable: 'common/setUpdateDataTable',
            setDataTables: 'common/setDataTables',
            setDataOrigins: 'common/setDataOrigins'
        }),
        changeType (val) {
            const params = {
                projectId: this.projectId,
                pageSize: -1
            }
            if (val === 1) {
                this.getDataTables(params)
            }
            if (val === 2) {
                this.getDataOrigins(params)
            }
        },
        getDataTables (params) {
            this.$post('/dataSource/file-upload/queryDataFileCatalog', params).then(res => {
                if (res) {
                    let arr = []
                    let list = res.subFiles.dataTables
                    for (let i = 0; i < list.length; i++) {
                        arr.push(...list[i].subFiles)
                    }
                    this.setDataTables(arr)
                }
            })
        },
        getDataOrigins (params) {
            this.$post('/dataSource/queryValidDataSources', params).then(res => {
                res && this.setDataOrigins(res)
            })
        },
        // 导入数据源
        handleUploadData (val) {
            this.resetForm()
            this.uploadData.form.dataType = val
            this.uploadData.show = true
            this.changeType(val)
        },
        // 数据源导入保存
        saveUpload () {
            const params = {
                projectId: this.projectId,
                tableName: this.uploadData.form.tableName
            }
            this.$post('/dataSource/existsDataTable', params).then(res => {
                if (res) {
                    this.$confirm('该表名已存在，确定使用此表名后，现有文件内容将会替换原文件，确定继续使用此表名吗？', '提示', {
                        confirmButtonText: '确 定',
                        cancelButtonText: '取 消',
                        type: 'warning'
                    }).then(() => {
                        this.handleSaveData()
                    }).catch(() => {})
                } else {
                    this.handleSaveData()
                }
            })
        },
        handleSaveData () {
            const {
                databaseSchema,
                characterEncoding,
                columnDelimiter,
                columnsException,
                dateFormat,
                description,
                existsHeader,
                filePath,
                fileType,
                tableName,
                timeFormat,
                timestampFormat,
                typeException,
                sourceId,
                srcTableName,
                dataType,
                splitKey,
                errorRecord,
                errorPercentage,
                parallelism,
                conditionExp,
                inputColumns,
                sparkExecutionNumber,
                sparkExecutionCores,
                sparkExecutionMemory,
                sparkDriverCores,
                sparkDriverMemory
            } = this.uploadData.form
            const { schema } = this.previewData
            let params = {
                characterEncoding,
                columnDelimiter,
                columnsException,
                dateFormat,
                description,
                existsHeader,
                filePath,
                fileType,
                projectId: this.projectId,
                schema,
                tableName,
                timeFormat,
                timestampFormat,
                typeException
            }
            let url = '/dataSource/file-upload/processDataFile'
            if (dataType === 2) {
                url = '/dataSource/file-upload/processDataTable'
                params = {
                    projectId: this.projectId,
                    sourceId,
                    srcTableName,
                    schema,
                    destTableName: tableName,
                    description,
                    databaseSchema,
                    splitKey,
                    errorRecord,
                    errorPercentage,
                    parallelism,
                    conditionExp,
                    inputColumns
                }
            }
            params = {
                ...params,
                sparkExecutionNumber,
                sparkExecutionCores,
                sparkExecutionMemory,
                sparkDriverCores,
                sparkDriverMemory
            }
            this.$post(url, params).then(res => {
                if (res) {
                    this.init()
                    this.$message.success('已提交至任务列表，可随时查看进度')
                    this.uploadData.show = false
                }
            })
        },
        resetForm () {
            this.uploadData.form = {
                dataType: null,
                databaseType: null,
                databaseSchema: null,
                fileList: [],
                limit: 100,
                filePath: null,
                srcTableName: null,
                sourceId: null,
                existsHeader: true,
                characterEncoding: 'UTF-8',
                timestampFormat: 'yyyy-MM-dd HH:mm:ss.SSS',
                timeFormat: 'yyyy-MM-dd HH:mm:ss',
                dateFormat: 'yyyy-MM-dd',
                columnDelimiter: null,
                fileType: null,
                description: null,
                filed: null,
                tableName: null,
                columnsException: 'Discard Row',
                typeException: 'Missing Value',
                splitKey: null,
                errorRecord: null,
                errorPercentage: null,
                parallelism: 1,
                conditionExp: null,
                inputColumns: [],
                splitKeyList: [],
                sparkExecutionNumber: 2,
                sparkExecutionCores: 2,
                sparkExecutionMemory: 1024,
                sparkDriverCores: 1,
                sparkDriverMemory: 1024
            }
        },
        handleReset () {
            this.isSearch = false
            this.keyword = ''
            this.tableData.currentPage = 1
            this.init()
        },
        search () {
            this.tableData.currentPage = 1
            this.isSearch = true
            this.init()
        },
        init () {
            this.loading = true
            const params = {
                projectId: this.projectId,
                keyword: this.keyword,
                pageSize: this.pageSize,
                pageNum: this.currentPage
            }
            this.$post('/dataSource/queryDataTables', params).then(res => {
                if (res) {
                    const {
                        total,
                        rows
                    } = res
                    this.total = total
                    this.tableData = rows
                }
            }).finally(() => {
                this.loading = false
            })
        },
        handleRemove (item) {
            this.$confirm(`确定要删除数据表<span>[${item.tableName}]</span>吗？`, '提示', {
                confirmButtonText: '确 定',
                cancelButtonText: '取 消',
                dangerouslyUseHTMLString: true,
                type: 'warning'
            }).then(() => {
                const params = {
                    projectId: this.projectId,
                    tableIds: [item.tableId]
                }
                this.$post('/dataSource/deleteDataTables', params).then(res => {
                    if (res) {
                        this.$message.success('删除成功')
                        this.init()
                        this.setUpdateDataTable(Math.random())
                    }
                })
            }).catch(() => {})
        },
        handleCurrentChange (val) {
            this.currentPage = val
            this.init()
        },
        handleSizeChange (val) {
            this.pageSize = val
            this.init()
        },
        seeDetail (item) {
            const params = {
                tableId: item.tableId,
                projectId: this.projectId
            }
            this.detailLoading = true
            this.$post('/dataSource/viewDataTable', params).then(res => {
                if (res) {
                    res.summary.table = res.table
                    this.dialogData = {
                        title: item.tableName,
                        show: true,
                        data: res.summary
                    }
                }
            }).finally(() => {
                this.detailLoading = false
            })
        },
        getSize (size) {
            let m = 0
            if (size) {
                if (size < 1024) {
                    m = `${size}B`
                } else if (size < 1048576) {
                    m = `${parseInt(size / 1024)}K`
                } else if (size < 1073741824) {
                    m = `${parseInt(size / 1048576)}M`
                } else {
                    m = `${parseInt(size / 1073741824)}G`
                }
            }
            return m
        }
    }
}
</script>

<style lang="less">
.data-home {
    height: 100%;
    overflow: hidden;
    .icon-shujuyuan {
        margin-right: 5px;
        font-size: 12px;
    }
    th {
        &.el-table-column--selection {
            .cell {
                opacity: 0;
            }
        }
    }
    .check-progress-btn {
        margin-left: 8px;
        font-size: 14px;
        color: #666;
        &:hover {
            color: #2680eb;
        }
    }
}
</style>
